 #include <netdb.h>
 #include <stdio.h>
 #include <signal.h>
 #include "common_func.h"
 #include "unix_svr.h"

static socklen_t socklen;
static TSockAddrUn unClientaddr;
static TSockAddr   *pSockAddr = NULL;
static int sockFd = -1;

int startServer()
{
    int iRet;

	TSockAddrUn serv_unadr;
	TSockAddrIn serv_inadr;
	TSockAddr   *pSockAddr = NULL;

	bzero(&serv_unadr,sizeof(serv_unadr));
	bzero(&serv_inadr,sizeof(serv_inadr));

	serv_unadr.sun_family = AF_UNIX;
	strcpy(serv_unadr.sun_path,UNIX_SOCKET_PATH);

	pSockAddr = (TSockAddr *)&serv_unadr;
	
	signal(SIGPIPE, SIG_IGN);


	/* 创建本地socket */
	sockFd = socket(AF_UNIX, SOCK_DGRAM, 0);//数据包方式
	if ( sockFd <= 0)
	{
	    perror("socket error");
	    return sockFd;
	}

	/* 绑定监听口 */
    int flag = 1;
    iRet = setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));

    setSocketAttr(sockFd);

    unlink(UNIX_SOCKET_PATH);
	iRet = bind(sockFd, pSockAddr, sizeof(TSockAddr));
	if (iRet != 0)
	{
	    perror("bind error");
		close(sockFd);
		return -1;
	}


    return sockFd;
}

//返回0 超时  timeOut-超时时间
int UnixRead(char *recvBuf, int len, int timeOut)
{
	int nRead = readable_timeo(sockFd, timeOut);
	if ( nRead <= 0 )
	{
		printf("UnixRead, read time out!\n");
		return 0;
	}

	pSockAddr = (TSockAddr *)&unClientaddr;
	socklen  = sizeof(TSockAddrUn);

	bzero(recvBuf, len);
	
	nRead = recvfrom(sockFd, recvBuf, len, 0, pSockAddr, &socklen);
	if ( nRead <= 0 )
	{
		if ( (EAGAIN == errno) || (EINTR == errno))
		{
			return 0;   //接收连接超时
		}

		perror("UnixRead read error:");
	}
	
	return nRead;
}

int UnixSend(const void *data, int len)
{
	return sendto(sockFd, data, len, 0, pSockAddr, socklen);
}

#ifdef _TEST_
int main()
{
	startServer();
	int nRead = 0;
	
	
	char recvBuf[1024] = {0}; 	
	
	while(1)
	{		
		nRead = UnixRead(recvBuf, 1024, 5);
		if ( nRead <= 0 )
		{
			continue;
		}
		else
		{
			printf("recv %d data: %s\n",nRead, recvBuf);
			const char *sendMsg = "svr ack!";
			UnixSend(sendMsg, strlen(sendMsg));
		}
		
		sleep(1);
	}
	
	
	
	return 0;
}
 #endif
 
 
 
 
 